package com.gszy.auth.database;

import com.gszy.auth.utils.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class BeanListHandler<T> implements ResultSetHandler<T> {
    private Class<?> beanClass;

    public BeanListHandler(Class<?> beanClass){
        this.beanClass = beanClass;
    }

    @Override
    public List<T> handler(ResultSet resultSet) {
        List<T> list = new ArrayList<>();
        try{
            while(resultSet.next()){
                //SysUser sysUser = new SysUser();
                T bean = (T) beanClass.newInstance();

                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();

                for (int i =1;i<columnCount;i++){
                    String columnName = metaData.getColumnName(i);

                    Object columValue = resultSet.getObject(columnName);

                    String s = StringUtils.toCamelCase(columnName);
                    //username bean.setUsername(columValue)
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(
                            s,beanClass
                    );

                    //setxxx
                    Method writeMethod = propertyDescriptor.getWriteMethod();

                    writeMethod.invoke(bean,columValue);
                }
                list.add(bean);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
}